'''
Created on Nov 9, 2010

@author: dexen
'''

from dexen.system.node.master.mgrs.ind_mgr import IndMgr
from dexen.system.node.master.mgrs.state_mgr import StateMgr
from dexen.system.node.master.mgrs.task_mgr import TaskMgr
from dexen.system.common.base import Individual


class MasterEnv(object):
    def __init__(self, state_mgr):
        assert isinstance(state_mgr, StateMgr)
        self._state_mgr = state_mgr
        self._task_mgr = state_mgr.get_task_mgr()
        self._ind_mgr = state_mgr.get_ind_mgr()
        self._has_changed = False
        self._updated_ids = set()
        self._archived = {}

    def archive_to_file(self, file_name, content):
        self._has_changed = True
        self._archived[file_name] = str(content)

    def set_slave_data(self, name, value):
        state_mgr = self._state_mgr
        assert isinstance(state_mgr, StateMgr)
        state_mgr.set_slave_data(name, value)

    def start_task(self, class_obj, label, input_size, valid_func):
        task_mgr = self._task_mgr
        assert isinstance(task_mgr, TaskMgr)
        task_mgr.start_task(class_obj, label, input_size, valid_func)
    
    def stop_task(self):
        pass
    
    def stop_master(self):
        self._has_changed = True
        state_mgr = self._state_mgr
        assert isinstance(state_mgr, StateMgr)
        state_mgr.finish()
    
    def set_ind(self, ind):
        self._has_changed = True
        ind_mgr = self._ind_mgr
        assert isinstance(ind_mgr, IndMgr)
        ind = ind_mgr.set_ind(ind)
        assert isinstance(ind, Individual)
        self._updated_ids.add(ind.__id__)
            
    def set_inds(self, inds):
        for ind in inds:
            self.set_ind(ind)
            
    def get_inds(self):
        pass
    
    def num_inds(self):
        ind_mgr = self._ind_mgr
        assert isinstance(ind_mgr, IndMgr)
        return ind_mgr.num_inds()
    
    def get_active_inds(self):
        pass
    
    def num_inactive_inds(self):
        pass

    def _get_archive(self):
        return self._archived
        
    def _get_updated_inds(self):
        ind_mgr = self._ind_mgr
        assert isinstance(ind_mgr, IndMgr)
        updated_inds = []
        for id in self._updated_ids:
            updated_inds.append(ind_mgr.get_ind(id))
        self._updated_ids = set()
        return updated_inds

    def _has_state_changed(self):
        return self._has_changed

    def _reset(self):
        self._has_changed = False
        self._archived = {}
        
        